﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
namespace FAP.Cores.Requesting
{
    public class Requester
    {
        private CookieContainer m_ccCookie = new CookieContainer();

        public Uri uri = null;
        private string cookieheader;

        public string Cookie
        {
            get
            {

                return cookieheader;
            }
        }

        public WebResponse GetData(String _strURL, bool _isUseProxy = false, string _ccCookie = null)
        {
            if (_ccCookie != null && _ccCookie.IndexOf(';')>-1)
            {
                _ccCookie = _ccCookie.Replace(';', ',');
            }
            uri = new Uri(_strURL);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.69 Safari/537.36";
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            request.Headers.Add("Accept-Language", "en-US,en;q=0.8");
            request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
            if (_isUseProxy)
                request.Proxy = new WebProxy("186.235.237.58", 8080);
            m_ccCookie = new CookieContainer();
            if (_ccCookie != null)
                m_ccCookie.SetCookies(uri, _ccCookie);
            request.CookieContainer = m_ccCookie;
            request.KeepAlive = true;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("Cache-Control", "max-age");
            request.Headers.Add("Origin", uri.Host);
            request.Method = "GET";
            try
            {
                WebResponse res = request.GetResponse();
            
                //if (res.Headers["Set-Cookie"] == null)
                  //  return res;

                var response = (HttpWebResponse)res;
                cookieheader = "";
                foreach (Cookie cookie in response.Cookies)
                {
                    //Console.WriteLine(cookie.Name + " = " + cookie.Value);
                    cookieheader += cookie.Name + "=" + cookie.Value + ",";
                }
                cookieheader = cookieheader.Remove(cookieheader.Length - 1, 1);
                m_ccCookie.SetCookies(uri, cookieheader);
               
                return res;
            }
            catch
            {
                return null;
            }
        }

        //hàm post
        public WebResponse PostData(String _strURL, String _strData, bool _isUseProxy = false, string _ccCookie = null)
        {
            if (_ccCookie != null && _ccCookie.IndexOf(';') > -1)
            {
                _ccCookie = _ccCookie.Replace(';', ',');
            }
            uri = new Uri(_strURL);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            byte[] data = Encoding.UTF8.GetBytes(_strData);//builder.ToString());

            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0";

            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

            request.Headers.Add("Accept-Language", "en-us,en;q=0.5");

            request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");

            request.KeepAlive = true;
            if (_isUseProxy)
                request.Proxy = new WebProxy("186.235.237.58", 8080);
            m_ccCookie = new CookieContainer();
            if (_ccCookie != null)
                m_ccCookie.SetCookies(uri, _ccCookie);
            request.CookieContainer = m_ccCookie;
            request.ContentType = "application/x-www-form-urlencoded";
            request.Referer = uri.AbsoluteUri;
            request.Headers.Add("Cache-Control", "max-age");
            request.ContentLength = data.Length;
            request.AllowAutoRedirect = false;


            request.Method = "POST";

            try
            {
                //thuong xay ra loi tai day (-_-)
                Stream stream = request.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();
            }
            catch (Exception ex)
            {
                return null;
            }

            try
            {
                WebResponse res = request.GetResponse();
              //  if (res.Headers["Set-Cookie"] == null)
               //     return res;
                var response = (HttpWebResponse)res;
                cookieheader = "";
                foreach (Cookie cookie in response.Cookies)
                {
                    //Console.WriteLine(cookie.Name + " = " + cookie.Value);
                    cookieheader += cookie.Name + "=" + cookie.Value + ",";
                }
                cookieheader = cookieheader.Remove(cookieheader.Length - 1, 1);
                m_ccCookie.SetCookies(uri, cookieheader);
                return res;
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        //tra ve ma html tu response
        public String GetHtmlFromResponse(WebResponse response)
        {
            Stream dataStream = null;
            try
            {
                dataStream = response.GetResponseStream();
            }
            catch
            {
                return null;
            }

            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);

            // Read the content.
            return reader.ReadToEnd();
        }
    }
}